package com.chr.hongyun.controller;

import cn.hutool.json.JSONUtil;
import com.chr.hongyun.common.utils.R;
import com.chr.hongyun.config.shiro.JwtUtil;
import com.chr.hongyun.controller.form.*;
import com.chr.hongyun.exception.HongyunException;
import com.chr.hongyun.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 员工管理控制层
 * 创建日期:2023/4/14
 * 创建人:陈浩然
 */
@RestController
@RequestMapping("/user")
@Api("员工模块Web接口")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${hongyun.jwt.cache-expire}")
    private int cacheExpire;

    @Value("${hongyun.jwt.expire}")
    private int expire;

    @PostMapping("/register")
    @ApiOperation("注册员工")
    public R register(@Valid @RequestBody RegisterForm form) {
        int id = userService.registerUser(form.getRegisterCode(), form.getCode(), form.getNickname(), form.getPhoto());
        String token = jwtUtil.createToken(id);
        Set<String> permsSet = userService.searchUserPermissions(id);
        saveCacheToken(token, id);
        return R.ok("员工注册成功").put("token", token).put("permission", permsSet);
    }

    @PostMapping("/login")
    @ApiOperation("登陆系统")
    public R login(@Valid @RequestBody LoginForm form) {
        int userId = userService.login(form.getCode());
        String token = redisTemplate.opsForValue().get(userId + "");
        if (token == null) {
            token = jwtUtil.createToken(userId);
            saveCacheToken(token, userId);
        }
        Set<String> permsSet = userService.searchUserPermissions(userId);
        return R.ok("登陆成功").put("token", token).put("permission", permsSet);
    }

    @GetMapping("/searchUserSummary")
    @ApiOperation("查询员工摘要信息")
    public R searchUserSummary(@RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        HashMap map = userService.searchUserSummary(userId);
        return R.ok().put("result", map);
    }

    @GetMapping("/searchUserInfo")
    @ApiOperation("查询员工基本信息")
    @RequiresPermissions("USER:SELECT")
    public R searchUserInfo(@RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        HashMap map = userService.searchUserInfo(userId);
        return R.ok().put("result", map);
    }

    @PostMapping("/searchUserGroupByDept")
    @ApiOperation("查询员工列表，按照部门分组排列")
    @RequiresPermissions(value = {"ROOT", "EMPLOYEE:SELECT"}, logical = Logical.OR)
    public R searchUserGroupByDept(@Valid @RequestBody SearchUserGroupByDeptForm form, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        ArrayList<HashMap> list = userService.searchUserGroupByDept(form.getKeyword(), userId);
        return R.ok().put("result", list);
    }

    @PostMapping("/searchMembers")
    @ApiOperation("查询成员")
    @RequiresPermissions(value = {"ROOT", "MEETING:INSERT", "MEETING:UPDATE"}, logical = Logical.OR)
    public R searchMembers(@Valid @RequestBody SearchMembersForm form) {
        if (!JSONUtil.isJsonArray(form.getMembers())) {
            throw new HongyunException("members不是JSON数组");
        }
        List param = JSONUtil.parseArray(form.getMembers()).toList(Integer.class);
        ArrayList list = userService.searchMembers(param);
        return R.ok().put("result", list);
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation("员工修改个人资料")
    @RequiresPermissions(value = "USER:UPDATE")
    public R updateUserInfo(@Valid @RequestBody UpdateUserInfoForm form, @RequestHeader("token") String token){
        if (form.getName() == null  || form.getName().length() == 0) {
            throw new HongyunException("姓名不能为空");
        }
        int userId = jwtUtil.getUserId(token);
        HashMap param = new HashMap();
        param.put("nickname", form.getNickname());
        param.put("name", form.getName());
        param.put("sex", "1".equals(form.getSex()) ? "男" : "女");
        param.put("tel", form.getTel());
        param.put("email", form.getEmail());
        param.put("id", userId);
        userService.updateUserInfo(param);
        return R.ok().put("result", "success");
    }


    private void saveCacheToken(String token, int userId) {
        redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(userId + "", token, expire, TimeUnit.DAYS);
    }

}
